//
//  ECNewListViewController.m
//  Edu_iOS2018
//
//  Created by apple on 2018/1/26.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECNewListViewController.h"

#import <AVFoundation/AVFoundation.h>

#import "CYUITVDSD_base.h"
#import "CYUITVDSDBridge.h"

#import "ECUCatalogModel.h"//model
#import "CourseModel.h"

#import "ECUFirstHeadCell.h"//cell
#import "ECUSecondHeadCell.h"
#import "ECUThirdHeadCell.h"

#import "ECUIVC_Show.h"
#import "ECUIVC_TextViewController.h"



extern CGFloat TABBAR_FOOTER_HEIGHT;

@interface ECNewListViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    ///存储正在播放中的model,当 视频播放完成/视频进行到一定长度 对服务器发送数据
    ECListModel *playingModel;
    ///是否加入学习
    BOOL isAddLearn;
    ///选中cell的Indexpath
    NSIndexPath *selectCellPath;
}

@property (nonatomic, strong) NSMutableArray <__kindof ECListModel *> *dataArray;

@end

@implementation ECNewListViewController
@synthesize tableView = _tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    _isMember = 2;
    playingModel = [[ECListModel alloc]init];
    selectCellPath = [[NSIndexPath alloc]init];
    
    [self getDataWithURL];
    
    [self setNotificationConfig];
}

/**
 添加通知
 */
-(void)setNotificationConfig{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];//注册视频播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:kNotifactionTextLearned object:nil];//注册进入文本页面完成之后 目录页面刷新对应数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userAddOrBuyLearn:) name:kNotifactionUserAddOrBuyLearn object:nil];//注册加入学习后通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userGoToLearn) name:kNotifactionUserGoToLearn object:nil];//立即学习通知
}

- (void)setIsMember:(NSInteger)isMember
{
    _isMember = isMember;
    if (isMember != 2) {
        [self catalogContainsFreeCourse];
        
    }
    
}
-(void)addSubviews{
    [super addSubviews];
    
    [self.view addSubview:self.tableView];
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, TABLEVIEWCONTENT_OFFSET_Y)];
    _tableView.tableHeaderView = headerView;
    
}

/*  加载数据  */
-(void)getDataWithURL{
    DLog(@"%@",[[UserInfoManager shareUser] token]);
    NSDictionary *headers = @{URL_SERVER_HEADER_USERTOKEN_KEY:[UserInfoManager shareUser].token?[UserInfoManager shareUser].token:@""};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HWHttpTool requestWithMethod:@"GET"
                              url:URL_GET_CourseUnitsWithId(self.courseModel.modelId)
                           params:nil
                          headers:headers
                          success:^(id json) {
                              
                              dispatch_async(dispatch_get_global_queue(0, 0), ^{
                                  // 处理耗时操作的代码块...
                                  NSMutableArray *arr = [[NSMutableArray alloc]init];
                                  [arr addObjectsFromArray:[ECListModel mj_objectArrayWithKeyValuesArray:json[@"data"]]];
                                  //循环所有数据 进行level分级
                                  for (int i = 0; i < arr.count; i++) {
                                      ECListModel *model = arr[i];
                                      if (i == 0) {
                                          model.level = 0;
                                          [self.dataArray addObject:model];
                                      }else{
                                          ECListModel *lastModel = self.dataArray.lastObject;
                                          if ([model.type isEqualToString:@"chapter"]) {
                                              model.level = 0;
                                          }else if ([model.type isEqualToString:@"unit"]){
                                              if ([lastModel.type isEqualToString:@"chapter"]) {
                                                  model.level = 1;
                                              }else if ([lastModel.type isEqualToString:@"unit"]){
                                                  model.level = lastModel.level;
                                              }else{
                                                  if (lastModel.level == 0) {
                                                      model.level = 0;
                                                  }else{
                                                      model.level = lastModel.level-1;
                                                  }
                                              }
                                          }else{
                                              if ([lastModel.type isEqualToString:@"chapter"]) {
                                                  model.level = 1;
                                              }else if ([lastModel.type isEqualToString:@"unit"]){
                                                  model.level = lastModel.level + 1;
                                              }else{
                                                  model.level = lastModel.level;
                                              }
                                          }
                                          [self.dataArray addObject:model];
                                      }
                                  }
                                  [self catalogContainsFreeCourse];
                              });
                    
                          } failure:^(NSError *error) {
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              
                              NSString *str = [ECData_Json requestErrorTipWith:error];
                              if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                  [MBProgressHUD showTipMessageInWindow:kAlertTipOfInternetFailure];
                              }
                          }];
}

-(void)catalogContainsFreeCourse{
    
    if (self.isMember != 2) {
        for (ECListModel *lastModel in self.dataArray) {
            //数据源中判断是否有免费课时(音频/视频/文本)
            
            if (([lastModel.type isEqualToString:@"video"] || [lastModel.type isEqualToString:@"audio"] || [lastModel.type isEqualToString:@"text"]) && [lastModel.data.free isEqualToString:@"1"]) {
                if(self.isMember == 1){
                    //发送 (免费试学按钮 是否显示) 通知
                    lastModel.data.free = @"0";
                } else if(self.isMember == 0) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:kNotifactionExistFreeLesson object:nil userInfo:@{@"isShowFreeLearnImage":@"yes"}];
                    break;

                    
                }
                
            }
        }
    }
    
    //通知主线程刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
}
#pragma mark tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ECListModel *foldCellModel = self.dataArray[indexPath.row];
    
    //在此区分cell格式
    if ([foldCellModel.type isEqualToString:@"chapter"]) {
        static NSString *firstCell_identifier = @"ECUFirstHeadCell";
        ECUFirstHeadCell *firstCell = [tableView dequeueReusableCellWithIdentifier:firstCell_identifier];
        if (!firstCell) {
            firstCell = [[ECUFirstHeadCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:firstCell_identifier];
        }
        [firstCell setDateOfCellWithModel:foldCellModel];
        return firstCell;
    }else if([foldCellModel.type isEqualToString:@"unit"]){
        static NSString *secondCell_identifier = @"ECUSecondHeadCell";
        ECUSecondHeadCell *secondCell = [tableView dequeueReusableCellWithIdentifier:secondCell_identifier];
        if (!secondCell) {
            secondCell = [[ECUSecondHeadCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:secondCell_identifier];
        }
        [secondCell setDateOfCellWithModel:foldCellModel];
        return secondCell;
    }else{
        static NSString *thirdCell_identifier = @"ECUThirdHeadCell";
        ECUThirdHeadCell *thirdCell = [tableView dequeueReusableCellWithIdentifier:thirdCell_identifier];
        if (!thirdCell) {
            thirdCell = [[ECUThirdHeadCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:thirdCell_identifier];
        }
        [thirdCell setDateOfCellWithModel:foldCellModel];
        return thirdCell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ECListModel *foldCellModel = self.dataArray[indexPath.row];
    
    if ([foldCellModel.type isEqualToString:@"unit"] || [foldCellModel.type isEqualToString:@"chapter"]) {
        return 150.f*KProportion1080_Heigh;
    }else {
        return 180.f*KProportion1080_Heigh;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ECListModel *foldCellModel = self.dataArray[indexPath.row];
    
    if ([foldCellModel.type isEqualToString:@"chapter"] || [foldCellModel.type isEqualToString:@"unit"]) {
        return;//点击章节其他cell无反应
    }
    
    if ([foldCellModel.type isEqualToString:@"testpaper"]){//试卷类型
        [MBProgressHUD showTipMessageInWindow:@"请登录学缘网网站练习"];
        return;
    }
    
    for (ECListModel *clearnLearnModel in self.dataArray) {//清除上一个的cell中islearning字段数据 正在学标识 当前目录只有一个
        clearnLearnModel.isLearning = @"";
    }
    
    ECUThirdHeadCell *cell = (ECUThirdHeadCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    selectCellPath = indexPath;
    
    [self.tableView reloadData];
    
    playingModel = foldCellModel;//对model进行赋值
    
    if (self.deadline == NO) {//课程未过期情况
        if ([foldCellModel.data.status isEqualToString:@"unpublished"]) {
            [MBProgressHUD showTipMessageInWindow:@"课程未发布,暂时不能观看"];
            return;
        }
        if ((self.courseModel.isMember) || ([playingModel.data.free isEqualToString:@"1"]) ||(isAddLearn == YES)) {//已经加入学习或为免费课时 直接观看
            if ([foldCellModel.type isEqualToString:@"video"]) {//判断视频类型
                //调取视频播放器 (在此之前 还应判断课程状态 是否为已购买等.....)(2018年01月26日16:09:24)
                if ([self.delegate respondsToSelector:@selector(didSelectOfCellWithModel:)]) {
                    [self.delegate didSelectOfCellWithModel:foldCellModel];
                    foldCellModel.isLearning = @"正在学";
                }
            }else if ([foldCellModel.type isEqualToString:@"audio"]){//音频类型
                //调用音频播放器
                if ([self.delegate respondsToSelector:@selector(didSelectOfCellWithModel:)]) {
                    [self.delegate didSelectOfCellWithModel:foldCellModel];
                    foldCellModel.isLearning = @"正在学";
                }
            }else if([foldCellModel.type isEqualToString:@"text"]){//图文类型
                if ([self.delegate respondsToSelector:@selector(didSelectOfCellWithPaperModel:)]) {
                    [self.delegate didSelectOfCellWithPaperModel:foldCellModel];
                }
//                ECUIVC_TextViewController *vc = [[ECUIVC_TextViewController alloc]init];
//                vc.foldCellModel = foldCellModel;
//                [self.navigationController pushViewController:vc animated:YES];
            }else{//点击
            }
            
            [cell didSelectOfCellWithLearnStatus:foldCellModel];//改变学习状态
            
        }else{//为收费课程,需加入学习之后 才可进行观看
            if (![[UserInfoManager shareUser] token]) {
                // 直接跳转登录页面
                [ECUIVC_Show isShowLoginVCAtViewController:self];
                return;
            }else{
                NSString *tipStr;
                if ([self.courseModel.price floatValue] > 0) {
                    tipStr = @"此课时需要购买课程后学习";
                }else if (isAddLearn == NO){
                    tipStr = @"此课时需要加入课程后学习";
                }
                [MBProgressHUD showTipMessageInWindow:tipStr timer:2];
            }
        }
    }else{//课程已过期
        [MBProgressHUD showTipMessageInWindow:@"该课程已过期"];
    }
}

#pragma mark 各类通知回调

/**
 *  视频播放完了 ,发送状态
 *
 *  @param notification 通知URL_POST_Courses_PlayFinish
 */
- (void)moviePlayDidEnd:(NSNotification *)notification{
    
    ECListModel *model_tmp = self.dataArray[selectCellPath.row];
    if ([model_tmp.data.learnStatus isEqualToString:@"finished"]) {//如果该课程为已学完状态,则返回
        model_tmp.isLearning = @"已学完";
        [self.tableView reloadData];

        return;
    }else{
    
        NSString *str = URL_CourseDetailWithId(self.courseModel.modelId);
        NSString *url = [NSString stringWithFormat:@"%@/%@/finish",str,playingModel.data.ID];//拼接参数
        NSString *token = [[UserInfoManager shareUser] token]? [[UserInfoManager shareUser] token]:@"";
        [HWHttpTool requestWithMethod:@"POST"
                                  url:url
                               params:nil
                              headers:@{@"X-AUTH-TOKEN": token}
                              success:^(id json) {
                                  //发送成功,改变对应状态
                                  model_tmp.data.learnStatus = @"finished";
                                  model_tmp.isLearning = @"已学完";
                                  [self.tableView reloadData];
                                  
                              }
                              failure:^(NSError *error) {
                                  NSString *str = [ECData_Json requestErrorTipWith:error];
                                  if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                      [MBProgressHUD showTipMessageInWindow:kAlertTipOfInternetFailure];
                                  }
                              }];
    }
}

/**
 *  加入学习之后 ,发送状态通知
 */
-(void)userAddOrBuyLearn:(NSNotification *)notification{
    isAddLearn = YES;
    self.isMember = 1;
}

/**
 *  立即学习之后 ,接收状态通知
 */
-(void)userGoToLearn{
    //获取列表中第一个视频/音频文件 进行播放
    for (int i = 0; i < self.dataArray.count; i++) {
        ECListModel *model = self.dataArray[i];
        if ([model.type isEqualToString:@"video"] || [model.type isEqualToString:@"audio"]) {
            NSIndexPath *path=[NSIndexPath indexPathForItem:i inSection:0];
            
            for (ECListModel *clearnLearnModel in self.dataArray) {//清除上一个的cell中islearning字段数据 正在学标识 当前目录只有一个
                clearnLearnModel.isLearning = @"";
            }
            //调用cell方法 改变cell状态
            ECUThirdHeadCell *cell = (ECUThirdHeadCell *)[self.tableView cellForRowAtIndexPath:path];
            model.isLearning = @"正在学";
            [cell didSelectOfCellWithLearnStatus:model];//改变学习状态
            
            //调取视频播放器
            if ([self.delegate respondsToSelector:@selector(didSelectOfCellWithModel:)]) {
                [self.delegate didSelectOfCellWithModel:model];
            }
            
            //给播放完成通知Path进行赋值
            selectCellPath = path;
            
            return;//跳出
        }
    }
}




#pragma mark 空页面占位图设置
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"Mine_emptyImage_SystemNoti"];
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state;{
    //在UILabel显示不同的字体和颜色
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"请求失败,点击重试"];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#b3b3b3"] range:NSMakeRange(0,9)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:16.0] range:NSMakeRange(0,9)];

    return [[NSAttributedString alloc]initWithAttributedString:str];
}

-(void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button{
    [button addTarget:self action:@selector(btnclick) forControlEvents:UIControlEventTouchUpInside];
}

/**
 重新加载
 */
-(void)btnclick{
    [self getDataWithURL];
}

-(void)tableViewDidScroll:(tableViewDidScrollBlock)scrollBlock{
    self.scrollBlock = scrollBlock;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.scrollBlock(scrollView.contentOffset.y);
}

#pragma mark 懒加载

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, self.view.height) style:UITableViewStylePlain];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.separatorStyle = 0;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

-(void)dealloc{
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotifactionUserAddOrBuyLearn object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotifactionUserGoToLearn object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotifactionTextLearned object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
